<template>
  <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
    <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="form.description" placeholder="请输入角色描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="identifyChange">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { addRoleApi, editRoleApi, getRoleDetailsApi } from '@/api/role'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    nodeData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: '',
        description: '',
        id: ''
      },
      rules: {
        name: [
          { required: true, message: '此项为必填项', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '此项为必填项', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  // 计算属性
  computed: {
    // 判断使添加还是修改
    showTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  methods: {
    // 关闭弹窗
    closeDialog() {
      this.form.id = ''
      this.$refs.roleForm.resetFields()
      this.$emit('update:showDialog', false)
    },
    // 点击确认表单校验
    identifyChange() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          await editRoleApi(this.form)
          this.$message.success('编辑成功')
          this.closeDialog()
          this.$emit('edit-role')
        } else {
          // 调用添加接口
          console.log(this.form)
          await addRoleApi(this.form)
          this.$message.success('添加成功')
          this.closeDialog()
          // 通知父组件刷新页面
          this.$emit('add-role')
        }
      })
    },
    // 封装获取角色详情
    async getRoleDetails() {
      const { data: res } = await getRoleDetailsApi(this.nodeData.id)
      this.form = res.data
    }
  }
}
</script>
